package com.hff.client;

import com.hff.utils.FileUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

    /*
    这是客户端
    */
public class File {

    public static String upload(String requestPath, String path) {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String TWO_HYPHENS = "--";
        String LINE_END = "\r\n";
        FileInputStream in = null;

        try {

            URL url = new URL(requestPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-type", "multipart/form-data; BOUNDARY=" + BOUNDARY);
            connection.connect();

            StringBuffer sb = new StringBuffer();

            String str = path.substring(path.lastIndexOf("/") + 1);
            //封装文件数据
            sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END);
            sb.append("Content-Disposition: form-data; name=\"file\"; filename=" + str).append(LINE_END);
            sb.append("Content-Type: file/*").append(LINE_END);
            sb.append(LINE_END);

            bytesToOutputStream(sb.toString().getBytes(), connection.getOutputStream());

            in = new FileInputStream(path);
            inputStreamToOutputStream(in, connection.getOutputStream());

            //写入标记结束位
            String end = (LINE_END + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END);
            bytesToOutputStream(end.getBytes(), connection.getOutputStream());

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                byte[] b = getBytesFromInputStream(connection.getInputStream());
                String back = new String(b);
                System.out.println("multi返回结果：" + back);
                String uuid = back;


//                String[] temp ;
//                back=back.replace("{","");
//                back=back.replace("}","");
//                temp=back.split(",");
//                for (int i = 0; i < temp.length; i++) {
//                  back=temp[2];
//                }
//                String trim = back.replace("\"", "").trim();
//                String uuid = null;
//                for (int i = 0; i < trim.split(":").length; i++) {
//                    uuid =trim.split(":")[1];
//
//                }
//                System.out.println(uuid);

                return uuid;
            } else {
                System.out.println("multi返回状态码：" + connection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtil.close(in);
        }
        return null;
    }


    public static void get(String requestPath) {
        try {

            URL url = new URL(requestPath);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                byte[] b = getBytesFromInputStream(connection.getInputStream());
                String back = new String(b);
                System.out.println("GET返回结果：" + back);
            } else {
                System.out.println("GET请求状态码：" + connection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 从输入流获取数据
     */
    private static byte[] getBytesFromInputStream(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        byte[] bytes = out.toByteArray();
        out.close();
        return bytes;
    }

    /**
     * 把字节数组写入输出流
     */
    private static void bytesToOutputStream(byte[] bytes, OutputStream out) throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
        in.close();
    }

    /**
     * 从输入流读取数据并写入输出流
     */
    private static void inputStreamToOutputStream(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
    }

    public static void main(String[] args) {

        //上传请求
        String requestUploadPath = "http://localhost:8080/file/upload";
        //下载请求
        String requestDownloadPath = "http://localhost:8080/file/download/";
        //获取元数据请求
        String requestDownGetFileDataPath = "http://localhost:8080/file/getFileData/";
        //需要上传的文件路径
        String path = "e:/04.jpg";
        //发送下载的post请求
        String uuid = upload(requestUploadPath, path);

        //发送下载的get请求
        get(requestDownloadPath + uuid);

        //发送获取元数据请求
        get(requestDownGetFileDataPath + uuid);


    }

}
